<template>
  <view class="content">
    <!-- 查询条件 -->
    <view class="search-box">
      <uni-search-bar 
        placeholder="请输入任务标题" 
        v-model="queryParams.title"
        @confirm="search"
      />
      <view class="filter-row">
        <uni-data-select
          v-model="queryParams.productId"
          placeholder="选择产品"
          :localdata="products"
        />
        <uni-data-select
          v-model="queryParams.orderId"
          placeholder="选择订单"
          :localdata="orders"
        />
        <button type="primary" @click="search">搜索</button>
      </view>
    </view>

    <!-- 数据表格 -->
    <view class="list-container">
      <view class="list-item" v-for="item in tableData" :key="item.id">
        <view class="item-header">
          <text class="item-title">{{ item.title }}</text>
          <uni-tag :text="statusMap[item.approvalStatus]" 
                  :type="statusTypeMap[item.approvalStatus]"/>
        </view>
        
        <view class="item-body">
          <view class="info-row">
            <text class="info-label">产品：</text>
            <text class="info-value">{{ item.productName }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">订单号：</text>
            <text class="info-value">{{ item.orderCoder }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">数量：</text>
            <text class="info-value">{{ item.actualQty }}{{ item.unit }}</text>
          </view>
        </view>

        <view class="item-actions">
          <button class="action-btn" size="mini" @click="showDetail(item)">查看详情</button>
          <!-- 提交按钮 -->
          <button v-if="item.approvalStatus === 0" 
                  class="action-btn" 
                  size="mini" 
                  type="primary"
                  @click="submitItem(item)">提交</button>
          <!-- 审批按钮 -->
          <!-- 审批按钮（待审批状态显示） -->
            <button v-if="item.approvalStatus === 1" 
                    class="action-btn" 
                    size="mini" 
                    type="warn"
                    @click="openApprovalDialog(item)">审批</button>
        </view>

        <!-- 详情展开面板 -->
        <view class="detail-panel" v-if="item.showDetail">
          <view class="detail-row">
            <text class="detail-label">上报时间：</text>
            <text>{{ formatTime(item.reportTime) }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">备注：</text>
            <text>{{ item.remark || '无' }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 审批弹窗 -->
    <uni-popup ref="approvalDialog" type="dialog">
      <uni-popup-dialog mode="form" title="任务审批" @confirm="submitApproval">
        <uni-forms ref="approvalForm" :model="approvalForm">
          <uni-forms-item label="审批结果" name="status" required>
            <uni-data-select 
              v-model="approvalForm.status" 
              :localdata="approvalOptions" 
              placeholder="请选择审批结果"
            />
          </uni-forms-item>
          <uni-forms-item label="审批意见" name="comment">
            <uni-easyinput 
              type="textarea" 
              v-model="approvalForm.comment" 
              placeholder="请输入审批意见"
              :styles="{height: '100px'}"
            />
          </uni-forms-item>
        </uni-forms>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      queryParams: {
        title: "",
        roleId: 2,
		workflowId: 2,
		productId: null,
		orderId: null
      },
      products: [],
      orders: [],
      tableData: [],
      approvalForm: {
        status: null,
        comment: '',
        currentItem: null
      },
      approvalOptions: [
        { text: '通过', value: 2 },
        { text: '驳回', value: 3 }
      ],
      statusMap: {
        0: '草稿',
        1: '待审批',
        2: '已通过',
        3: '已驳回'
      },
      statusTypeMap: {
        0: 'warning',
        1: 'primary',
        2: 'success',
        3: 'error'
      }
    }
  },
  methods: {
    // 初始化数据
	// 新增产品加载方法
	    async loadProducts() {
	      try {
	        const res = await uni.request({
	          url: 'http://localhost:1003/product/findAllProduct',
	          method: 'GET'
	        })
	        
	        if (res.data.code === 200) {
	          this.products = res.data.data.map(product => ({
	            text: product.productName,
	            value: product.id
	          }))
	        }
	      } catch (e) {
	        console.error('产品加载失败:', e)
	        uni.showToast({ title: '产品数据加载失败', icon: 'none' })
	      }
	    },
		// 新增订单加载方法
		    async loadOrder() {
		      try {
		        const res = await uni.request({
		          url: 'http://localhost:1003/order/findAllOrder',
		          method: 'GET'
		        })
		        
		        if (res.data.code === 200) {
		          this.orders = res.data.data.map(order => ({
		            text: order.orderNumber,
		            value: order.id
		          }))
		        }
		      } catch (e) {
		        console.error('产品加载失败:', e)
		        uni.showToast({ title: '产品数据加载失败', icon: 'none' })
		      }
		    },
	
	
    // 在loadData方法中修改：
    async loadData() {
      try {
        const res = await uni.request({
          url: 'http://localhost:1101/reportSummary/findListByRoleId',
          method: 'GET',
          data: this.queryParams
        });
        
        if (res.data.code === 200) {
          // 修改这里：res.data.data 替换原来的 res.data.rows
          this.tableData = res.data.data.map(item => ({
            ...item,
            showDetail: false,
            // 添加单位字段的默认值（根据实际情况）
            unit: item.unit || '件'
          }));
        }
      } catch (e) {
        console.error('加载数据失败:', e);
        uni.showToast({ title: '数据加载失败', icon: 'none' });
      }
    },
    // 搜索
    search() {
      this.loadData();
    },

    // 显示详情
    showDetail(item) {
      item.showDetail = !item.showDetail;
    },

    // 格式化时间
   // 新增时间格式化方法
    formatTime(time) {
        const date = new Date(time);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      },

    // 提交条目
    async submitItem(item) {
      try {
        await uni.request({
          url: 'http://localhost:1101/reportSummary/submit',
          method: 'POST',
          data: { id: item.id }
        });
        this.loadData();
        uni.showToast({ title: '提交成功' });
      } catch (e) {
        console.error('提交失败:', e);
        uni.showToast({ title: '提交失败', icon: 'none' });
      }
    },

    // 打开审批对话框
    openApprovalDialog(item) {
      this.approvalForm = {
        status: null,
        comment: '',
        currentItem: item
      };
      this.$refs.approvalDialog.open();
    },

    // 提交审批
    async submitApproval() {
      try {
        const valid = await this.$refs.approvalForm.validate();
        if (!valid) return;

        uni.showLoading({ title: '提交中...' });
       
        await this.updateApprovalStatus();
        await this.addApprovalProcess();
        
        uni.showToast({ title: '审批完成' });
        this.$refs.approvalDialog.close();
        this.loadData();
      } catch (e) {
        console.error('审批出错:', e);
        uni.showToast({ title: '审批失败', icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    },

    // 更新任务下一个流程状态
    // 修改updateApprovalStatus方法
    updateApprovalStatus() {
      return new Promise((resolve, reject) => {
        const payload = {
          id: this.approvalForm.currentItem.id,
          approvalStatus: this.approvalForm.status,
		  workflowId: 2
        }
        uni.request({
          url: 'http://localhost:1101/reportSummary/updateReportSummary',
          method: 'POST',
          data: payload,
          success: (res) => {
            res.data.code === 200 ? resolve() : reject(res.data.msg);
          },
          fail: reject
        });
      });
    },

    // 添加审批流程记录
    addApprovalProcess() {
      return new Promise((resolve, reject) => {
        const userIdInfo = uni.getStorageSync('userIdInfo');
        uni.request({
          url: 'http://localhost:1101/reportProcess/save',
          method: 'POST',
          data: {
            reportId: this.approvalForm.currentItem.id,
            approverId: userIdInfo.userId,
            approverRoleId: 2,
            approvalStatus: this.approvalForm.status,
            approvalComments: this.approvalForm.comment,
            processStep: 2,
            createdBy: userIdInfo.userId,
			processId: 2,
          },
          success: (res) => {
            res.data.code === 200 ? resolve() : reject(res.data.msg);
          },
          fail: reject
        });
      });
    }
  },
  mounted() {
    this.loadData();
	this.loadProducts()
	this.loadOrder()
  }
}
</script>

<style scoped>
.content {
  padding: 20rpx;
}

.search-box {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-top: 20rpx;
}

.list-container {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
}

.list-item {
  border-bottom: 1px solid #eee;
  padding: 20rpx 0;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.item-title {
  font-size: 32rpx;
  font-weight: bold;
}

.item-body {
  margin-bottom: 15rpx;
}

.info-row {
  display: flex;
  margin: 10rpx 0;
}

.info-label {
  color: #666;
  min-width: 120rpx;
}

.info-value {
  color: #333;
}

.item-actions {
  display: flex;
  gap: 15rpx;
  justify-content: flex-end;
}

.action-btn {
  flex: none;
}

.detail-panel {
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  margin-top: 15rpx;
}

.detail-row {
  margin: 10rpx 0;
  color: #666;
}

.uni-forms-item__label {
  font-weight: bold;
  color: #333;
}

.uni-textarea {
  height: 100px;
  padding: 8px;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
}
</style>